﻿namespace DCHealthCheck.DomainModel {

    #region Usings
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Diagnostics;
    using System.Text;
    #endregion

    [Table("Certificate")]
    public class Certificate : ICertificate, IObjectWithState, IValidatableObject {

        #region Members
        #region Max length fields
        public static readonly int FriendlyNameMaxLength = 1024;
        public static readonly int IssuerNameMaxLength = 1024;
        public static readonly int SerialNumberMaxLength = 1024;
        public static readonly int SubjectNameMaxLength = 1024;
        public static readonly int ThumbprintMaxLength = 1024;
        #endregion

        public virtual string FriendlyName { get; set; }

        public virtual long Id { get; set; }

        public virtual DateTime EffectiveDate { get; set; }

        public virtual DateTime ExpirationDate { get; set; }

        public virtual string IssuerName { get; set; }

        public virtual string PublicKey { get; set; }

        public virtual string SerialNumber { get; set; }

        public virtual string SubjectName { get; set; }

        public virtual string Thumbprint { get; set; }

        public virtual byte[] X509CertificateRawData { get; set; }

        #region Related Entities
        [ForeignKey("SystemInfo")]
        public virtual Guid SystemInfoId {
            get {
                if (this.SystemInfo != null) return this.SystemInfo.Id;
                return systemInfoId;
            }
            set { systemInfoId = value; }
        }
        private Guid systemInfoId;
        public virtual SystemInfo SystemInfo {
            get { return systemInfo; }
            set {
                systemInfo = value;
                if (systemInfo != null) {
                    if (this.SystemInfoId != systemInfo.Id) {
                        this.SystemInfoId = systemInfo.Id;
                    }
                }
            }
        }
        private SystemInfo systemInfo;
        #endregion

        #region NotMapped properties
        [NotMapped]
        public DetachedState DetachedState { get; set; }

        [NotMapped]
        public Object EntityKey { get { return this.Id; } }

        [NotMapped]
        public Dictionary<string, object> StartingOriginalValues { get; set; }
        #endregion
        #endregion

        #region Constructor
        public Certificate() {
            this.FriendlyName = string.Empty;
            this.IssuerName = string.Empty;
            this.PublicKey = string.Empty;
            this.SerialNumber = string.Empty;
            this.SubjectName = string.Empty;
            this.Thumbprint = string.Empty;
        }
        #endregion

        #region Methods
        [DebuggerStepThroughAttribute]
        public override string ToString() {
            var info = new StringBuilder();

            info.Append("Certificate:  ");
            if ((this.SystemInfo != null) && (this.SystemInfo.DomainController != null) && (this.SystemInfo.DomainController.SamAccountNameFriendly != null)) {
                info.AppendFormat("DC: {0}; ", this.SystemInfo.DomainController.DNSName);
            }
            if (this.SystemInfo != null) {
                info.AppendFormat("HealthCheck Date: {0}; ", this.SystemInfo.CheckDateTimeUTC.ToString("yyyy-MMM-dd"));
            }
            info.AppendFormat("Friendly Name: {0};", this.FriendlyName ?? "NULL");
            info.AppendFormat("Subject Name: {0};", this.SubjectName ?? "NULL");
            info.AppendFormat("Issuer Name: {0};", this.IssuerName ?? "NULL");
            info.AppendFormat("Expiration Date: {0};", this.ExpirationDate.ToString("yyyy-MM-DD"));

            return info.ToString();
        }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
            if ((this.DetachedState != DetachedState.Added) && (this.Id < 1)) {
                yield return new ValidationResult(
                    "Id is required.", new[] { "Id" });
            }

            if (this.DetachedState != DetachedState.Deleted) {
                // add entity to SystemInfo, let DetectChanges perform relationship fixup
                if (this.SystemInfoId == Guid.Empty) {
                    yield return new ValidationResult(
                        "SystemInfoId is required.", new[] { "SystemInfoId" });
                }

                if ((this.SystemInfo != null) && (this.SystemInfo.Id != this.SystemInfoId)) {
                    yield return new ValidationResult(
                        "SystemInfo.Id does not match SystemInfoId.", new[] { "SystemInfo, SystemInfoId" });
                }

                if (this.FriendlyName == null) {
                    yield return new ValidationResult(
                        "FriendlyName is required.", new[] { "FriendlyName" });
                }
                else if (this.FriendlyName.Length > FriendlyNameMaxLength) {
                    yield return new ValidationResult(string.Format("FriendlyName length: {0} exceeds max length: {1}",
                        this.FriendlyName.Length, FriendlyNameMaxLength), new[] { "FriendlyName" });
                }

                if (string.IsNullOrWhiteSpace(this.IssuerName)) {
                    yield return new ValidationResult(
                        "IssuerName is required.", new[] { "IssuerName" });
                }
                else if (this.IssuerName.Length > IssuerNameMaxLength) {
                    yield return new ValidationResult(string.Format("IssuerName length: {0} exceeds max length: {1}",
                        this.IssuerName.Length, IssuerNameMaxLength), new[] { "IssuerName" });
                }

                if (this.SerialNumber == null) {
                    yield return new ValidationResult(
                        "SerialNumber is required.", new[] { "SerialNumber" });
                }
                else if (this.SerialNumber.Length > SerialNumberMaxLength) {
                    yield return new ValidationResult(string.Format("SerialNumber length: {0} exceeds max length: {1}",
                        this.SerialNumber.Length, SerialNumberMaxLength), new[] { "SerialNumber" });
                }

                if (string.IsNullOrWhiteSpace(this.SubjectName)) {
                    yield return new ValidationResult(
                        "SubjectName is required.", new[] { "SubjectName" });
                }
                else if (this.SubjectName.Length > SubjectNameMaxLength) {
                    yield return new ValidationResult(string.Format("SubjectName length: {0} exceeds max length: {1}",
                        this.SubjectName.Length, SubjectNameMaxLength), new[] { "SubjectName" });
                }

                if (string.IsNullOrWhiteSpace(this.Thumbprint)) {
                    yield return new ValidationResult(
                        "Thumbprint is required.", new[] { "Thumbprint" });
                }
                else if (this.Thumbprint.Length > ThumbprintMaxLength) {
                    yield return new ValidationResult(string.Format("Thumbprint length: {0} exceeds max length: {1}",
                        this.Thumbprint.Length, ThumbprintMaxLength), new[] { "Thumbprint" });
                }

                if ((this.X509CertificateRawData == null) || (this.X509CertificateRawData.Length == 0)) {
                    yield return new ValidationResult(
                        "X509CertificateRawData is required.", new[] { "X509CertificateRawData" });
                }
            } // if (this.DetachedState != State.Deleted)
        }
        #endregion

    }
}
